package com.cssnj.portal.service.login;

import com.cssnj.portal.domain.common.UserInfo;
import com.cssnj.portal.utils.PortalUntil;
import com.cssnj.portal.utils.RedisUtil;
import io.predictech.framework.domain.common.JsonRequest;
import io.predictech.framework.domain.common.JsonResponse;
import io.predictech.framework.domain.common.TreeNode;
import io.predictech.framework.domain.constants.SysConstants;
import io.predictech.framework.service.base.BaseService;
import io.predictech.framework.domain.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.*;

@Service("loginService")
public class LoginService extends BaseService {

    //国税数据源
    @Qualifier("secondJdbcTemplate")
    @Autowired
    private JdbcTemplate secondJdbcTemplate;

    //地税数据源
    @Qualifier("thirdJdbcTemplate")
    @Autowired
    private JdbcTemplate thirdJdbcTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    protected JsonResponse invokingService(JsonRequest jsonRequest) throws SQLException, BaseException {
        if ("loginIn".equals(jsonRequest.getHandleCode())) {
            return loginIn(jsonRequest);
        } else if ("loginInBySwsf".equals(jsonRequest.getHandleCode())) {
            return loginInBySwsf(jsonRequest);
        }
        return null;
    }

    private JsonResponse loginIn(JsonRequest jsonRequest) throws SQLException {
        JsonResponse jsonResponse = new JsonResponse();
        String userName = String.valueOf(jsonRequest.getReqData().get("userName"));
        String passWord = String.valueOf(jsonRequest.getReqData().get("passWord"));
        String ip = String.valueOf(jsonRequest.getReqData().get("ip"));

        List<Object> paramList = new ArrayList<>();
        paramList.add(userName);
        paramList.add(passWord);

        //根据用户名密码查询身份
        //查询国税身份
        List<Map<String, Object>> swrysfList = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = null;
        SqlRowSet rs = queryDao.queryForRowSet(secondJdbcTemplate, "SELECT '1,' || T.SWRYSF_DM SWRYSF_DM,T.RYSFMC RYSFMC FROM HX_QX.DM_QX_SWRYSF T, HX_QX.QX_DLZHXX S WHERE T.SWRY_DM = S.SWRY_DM AND T.YXBZ = 'Y' AND S.DLZH_DM = ? AND S.DLZHKL = ? AND S.YXBZ = 'Y'  ORDER BY XSXH", paramList);
        while (rs.next()) {
            map = new HashMap<String, Object>();
            map.put("SWRYSF_DM", rs.getString("SWRYSF_DM"));
            map.put("RYSFMC", rs.getString("RYSFMC"));
            map.put("isGs", "1");
            swrysfList.add(map);
        }
        //查询地税身份
        rs = queryDao.queryForRowSet(thirdJdbcTemplate, "SELECT '0,' || T.SWRYSF_DM SWRYSF_DM,T.RYSFMC RYSFMC FROM HX_QX.DM_QX_SWRYSF T, HX_QX.QX_DLZHXX S WHERE T.SWRY_DM = S.SWRY_DM AND T.YXBZ = 'Y' AND S.DLZH_DM = ? AND S.DLZHKL = ? AND S.YXBZ = 'Y'  ORDER BY XSXH", paramList);
        while (rs.next()) {
            map = new HashMap<String, Object>();
            map.put("SWRYSF_DM", rs.getString("SWRYSF_DM"));
            map.put("RYSFMC", rs.getString("RYSFMC"));
            map.put("isGs", "0");
            swrysfList.add(map);
        }

        if (swrysfList.size() == 0) { //用户名或账号不存在
            jsonResponse.setCode("W1001");
            jsonResponse.setMsg(this.getXxnr("W1001"));
            this.saveLog(this.getRznr("W0001", userName + "$" + ip), userName, "W0001");
            PortalUntil.logger().info("用户名或账号不存在");
            return jsonResponse;
        }
        if (swrysfList.size() == 1) {
            //单一身份用户
            String[] starr = swrysfList.get(0).get("SWRYSF_DM").toString().split(",");
            UserInfo userInfo = getUserInfo(starr[1], ip, starr[0]);
            if (userInfo.getGwlist().size() == 0) {//没有岗位
                jsonResponse.setCode("W1099");
                jsonResponse.setMsg("用户身份未配置岗位");
                PortalUntil.logger().info("用户身份未配置岗位");
            } else if (userInfo.getRole().size() == 0) {//没有角色
                jsonResponse.setCode("W1100");
                jsonResponse.setMsg("用户身份未配置角色");
                PortalUntil.logger().info("用户身份未配置角色");
            } else {
                jsonResponse.getRepData().put("userInfo", userInfo);
                jsonResponse.getRepData().put("isGs", swrysfList.get(0).get("isGs").toString());
            }
        } else {
            jsonResponse.getRepData().put("swrysfList", swrysfList);
        }
        return jsonResponse;

    }

    private UserInfo getUserInfo(String swrysfDm, String ip, String isGs) throws SQLException {
        JdbcTemplate queryJdbcTemplate = secondJdbcTemplate;
        if ("0".equals(isGs)) {//地税
            queryJdbcTemplate = thirdJdbcTemplate;
        }
        StringBuffer sqlGrxx = new StringBuffer(
                " SELECT A.DLZH_DM DLZHDM,A.SWRY_DM SWRYDM,B.SWRYXM SWRYXM,     \n" +
                "    C.SWRYSF_DM SWRYSFDM, C.RYSFMC SWRYSFMC,                   \n" +
                "    C.SFSWJG_DM SFSWJGDM,D.SWJGMC SFSWJGMC, D.JGJC_DM SFJGJCDM \n" +
                "  FROM HX_QX.QX_DLZHXX A,        \n" +
                "       HX_DM_ZDY.DM_GY_SWRY B,   \n" +
                "       HX_QX.DM_QX_SWRYSF C,     \n" +
                "       HX_DM_ZDY.DM_GY_SWJG D    \n" +
                " WHERE A.SWRY_DM = B.SWRY_DM     \n" +
                "   AND B.SWRY_DM = C.SWRY_DM     \n" +
                "   AND C.SFSWJG_DM= D.SWJG_DM(+) \n" +
                "   AND A.YXBZ='Y' \n" +
                "   AND B.YXBZ='Y' \n" +
                "   AND C.YXBZ='Y' \n" +
                "   AND C.SWRYSF_DM = ? ");

        List<Object> params = new ArrayList<Object>();
        params.add(swrysfDm);
        UserInfo userInfo = (UserInfo) queryDao.queryForObject(queryJdbcTemplate, sqlGrxx.toString(), params, UserInfo.class);
        //添加岗位信息
        sqlGrxx = new StringBuffer(
                " SELECT DISTINCT   B.GW_DM, D.GWMC, D.GWFL_DM, B.SWJG_DM, E.SWJGMC\n" +
                        "  FROM HX_QX.QX_SWJG_GW     B,\n" +
                        "       HX_DM_ZDY.DM_QX_GW   D,\n" +
                        "       HX_DM_ZDY.DM_GY_SWJG E\n" +
                        " WHERE B.GWXH IN (SELECT A.GWXH\n" +
                        "                    FROM HX_QX.QX_JGGW_SWRYSF A\n" +
                        "                   WHERE A.SWRYSF_DM = ?\n" +
                        "                     AND A.YXBZ = 'Y')\n" +
                        "   AND B.SWJG_DM = E.SWJG_DM(+)\n" +
                        "   AND E.YXBZ = 'Y'\n" +
                        "   AND B.GW_DM = D.GW_DM(+)\n" +
                        "   AND D.YXBZ = 'Y'\n");
        List<Map<String, Object>> gwlist = queryDao.queryForList(queryJdbcTemplate, sqlGrxx.toString(), params);
        userInfo.setGwlist(gwlist);
        if (gwlist.size() == 0) {
            return userInfo;
        }
        List<String> gwParams = new ArrayList<String>();
        for (int i = 0; i < gwlist.size(); i++) {
            gwParams.add(gwlist.get(i).get("GW_DM").toString());
        }
        if (gwParams.size() > 0) {
            Map<String, Object> sqlparam = new HashMap<String, Object>();
            sqlparam.put("GW_DM", gwParams);
            //查询角色
            Set<String> role = new HashSet<>();
            sqlGrxx = new StringBuffer("SELECT A.JS_ID FROM GL_GW_JS A,GL_JS B WHERE A.GW_ID IN (:GW_DM ) AND A.JS_ID =B.JS_ID AND B.ZTBJ_DM='1' ");
            List<Map<String, Object>> list = this.queryDao.queryForList(sqlGrxx.toString(), sqlparam);
            String js_id;
            for (int i = 0; i < list.size(); i++) {
                js_id = list.get(i).get("JS_ID").toString();
                role.add(js_id);
            }
            userInfo.setRole(role);
            if (role.size() == 0) {
                return userInfo;
            }
            sqlparam.clear();
            if (role.contains(SysConstants.SYS_USER_ADMIN)) {//管理员查询全部可以菜单
                list = queryDao.queryForList(
                        " SELECT GN_ID, GN_MC, SJGN_ID,  HREF, OPEN_TYPE , (CASE WHEN JDYS IS NOT NULL THEN 'noBack ' END)||DECODE(SJGN_ID,'0','ml ','')||JDYS ICONCLS, XT_DM SYSCODE,PX" +
                                "  FROM GL_GN " +
                                " WHERE XY_BJ = '1'  AND XS_BJ='1' ORDER BY DECODE(OPEN_TYPE,'0',0,1), PX ", sqlparam);
            } else {
                sqlparam.put("ROLE", role);
                list = queryDao.queryForList("SELECT A.GN_ID, A.GN_MC, A.SJGN_ID, A.HREF, A.OPEN_TYPE,(CASE WHEN JDYS IS NOT NULL THEN 'noBack ' END)||DECODE(SJGN_ID,'0','ml ','')||JDYS ICONCLS,XT_DM SYSCODE ,PX FROM GL_GN A ,GL_JS_GN B  " +
                        "    WHERE A.GN_ID = B.GN_ID AND A.XY_BJ='1'  AND A.XS_BJ='1'  AND B.JS_ID IN (:ROLE) " +
                        " ORDER BY DECODE(OPEN_TYPE,'0',0,1), PX ", sqlparam);
            }
            List<Map<String, Object>> userGnList = new ArrayList<Map<String, Object>>();
            Set<String> permissions = new HashSet<String>();
            Map<String, Object> dmap;
            for (Map<String, Object> data : list) {
                permissions.add((String) data.get("HREF"));
                dmap = new HashMap<String, Object>();
                dmap.put(TreeNode.ID.getKey(), data.get("GN_ID"));
                dmap.put(TreeNode.TEXT.getKey(), data.get("GN_MC"));
                dmap.put(TreeNode.PID.getKey(), data.get("SJGN_ID"));
                dmap.put(TreeNode.MODE.getKey(), data.get("OPEN_TYPE"));
                dmap.put(TreeNode.ICONCLS.getKey(), data.get("ICONCLS"));
                dmap.put(TreeNode.HREF.getKey(), data.get("HREF"));
                dmap.put(TreeNode.TEXT_REAL.getKey(), data.get("GN_MC"));
                dmap.put(TreeNode.SYSCODE.getKey(), data.get("SYSCODE"));
                if ("0".equals(dmap.get(TreeNode.MODE.getKey()))) {
                    dmap.put(TreeNode.CHILDREN.getKey(), new ArrayList<Map<String, Object>>());
                    dmap.put(TreeNode.STATE.getKey(), "closed");
                }
                dmap.put(TreeNode.SORT.getKey(), data.get("PX"));
                userGnList.add(dmap);
            }
            userInfo.setPermissions(permissions);
            RedisUtil.setUserTreelist(redisTemplate, userGnList, userInfo.getSwrySfDm());
        }

        //对照身份代码
        params.clear();
        params.add(userInfo.getSfswJgDm());
        if (userInfo.getSfswJgDm().startsWith("2")) {//"0".equals(isGs)
            List<Map<String, Object>> dzlist = queryDao.queryForList(queryJdbcTemplate, "SELECT MBDZGSWJG_DM SFSWJGDMDZ FROM HX_CS_ZDY.CS_DJ_GDSZGSWJGFPDZB WHERE YDZGSWJG_DM=?", params);
            if (dzlist.size() > 0) {
                userInfo.setSfswJgDmDz((String) dzlist.get(0).get("SFSWJGDMDZ"));
            }
        } else {
            List<Map<String, Object>> dzlist = queryDao.queryForList(queryJdbcTemplate, "SELECT YDZGSWJG_DM SFSWJGDMDZ FROM HX_CS_ZDY.CS_DJ_GDSZGSWJGFPDZB WHERE MBDZGSWJG_DM=?", params);
            if (dzlist.size() > 0) {
                userInfo.setSfswJgDmDz((String) dzlist.get(0).get("SFSWJGDMDZ"));
            }
        }

        String jgjcdm = userInfo.getSfJgjcDm();
        if("11".equals(jgjcdm)||"12".equals(jgjcdm)){
            userInfo.setJgfwdm(userInfo.getSfswJgDm().substring(0,3));
            userInfo.setCxjgDm(userInfo.getSfswJgDm().substring(0,3)+"00000000");
        }else if("31".equals(jgjcdm)||"32".equals(jgjcdm)){
            userInfo.setJgfwdm(userInfo.getSfswJgDm().substring(0,5));
            userInfo.setCxjgDm(userInfo.getSfswJgDm().substring(0,5)+"000000");
        }else{
            userInfo.setJgfwdm(userInfo.getSfswJgDm().substring(0,7));
            userInfo.setCxjgDm(userInfo.getSfswJgDm().substring(0,7)+"0000");
        }

        Set<String> role =userInfo.getRole();
        List<Map<String,Object>> loginOutList = null;
        Map<String, Object> sqlparam = new HashMap<String, Object>();
        if (role.contains(SysConstants.SYS_USER_ADMIN)) {//管理员查询全部可以菜单
            loginOutList = queryDao.queryForList(
                    " SELECT YY_MC,YY_GW||ZX_DZ ZXDZ FROM YY_JCXX WHERE XY_BJ='1' AND YY_ID IN ( \n"+
                            "   SELECT DISTINCT XT_DM  FROM GL_GN WHERE XY_BJ = '1'  AND XS_BJ='1' \n" +
                            " )\n", sqlparam);
        } else {
            sqlparam.put("ROLE", role);
            loginOutList = queryDao.queryForList(
                    " SELECT YY_MC,YY_GW||ZX_DZ ZXDZ FROM YY_JCXX WHERE XY_BJ='1' AND YY_ID IN ( \n"+
                            "   SELECT DISTINCT XT_DM FROM GL_GN A ,GL_JS_GN B  \n" +
                            "     WHERE A.GN_ID = B.GN_ID AND A.XY_BJ='1'  AND A.XS_BJ='1' \n" +
                            "    AND B.JS_ID IN (:ROLE) \n"+
                            " )\n", sqlparam);
        }
        userInfo.setLoginOutList(loginOutList);

        this.saveLog(this.getRznr("I0001", userInfo.getAuthId() + "$" + ip), userInfo.getDlzhDm(), "I0001");
        return userInfo;

    }


    private JsonResponse loginInBySwsf(JsonRequest jsonRequest) throws SQLException {
        JsonResponse jsonResponse = new JsonResponse();
        String str = (String) jsonRequest.getReqData().get("swrysfDm");
        String[] strarr = str.split(",");
        String isGs = strarr[0];
        String swrysfDm = strarr[1];
        //单一身份用户
        UserInfo userInfo = getUserInfo(swrysfDm, jsonRequest.getReqData().get("ip").toString(), isGs);
        if (userInfo.getGwlist().size() == 0) {//没有岗位
            jsonResponse.setCode("W1099");
            jsonResponse.setMsg("用户身份未配置岗位");
            PortalUntil.logger().info("用户身份未配置岗位");
        } else if (userInfo.getRole().size() == 0) {//没有角色
            jsonResponse.setCode("W1100");
            jsonResponse.setMsg("用户身份未配置角色");
            PortalUntil.logger().info("用户身份未配置角色");
        } else {
            jsonResponse.getRepData().put("userInfo", userInfo);
            jsonResponse.getRepData().put("isGs", isGs);
        }
        return jsonResponse;
    }


}
